﻿ExtJ = {};
ExtJ = function() {
	// public interface
	return {
		getContextPath : function() {
			return CONTEXT_PATH;
		},
		
		getRandomNo : function() {
			var myDate = new Date();
			var year = myDate.getFullYear();
			var month = myDate.getMonth() + 1;
			var day = myDate.getDate();
			if (month < 10) {
				month = '0' + month;
			}
			if (day < 10) {
				day = '0' + day;
			}
			var h = myDate.getHours();
			var m = myDate.getMinutes();
			var s = myDate.getSeconds();
			var random = year + '' + month + '' + day + '' + h + '' + m + ''
					+ s + '' + Math.round(Math.random() * 10000) + ''
					+ Math.round(Math.random() * 10000);
			return random;
		},


		getActionPath : function(action, p) {
			url = this.getContextPath() + "/" + action;
			if (typeof p == "function") {
				p = p.call(o.scope || window, o);
			}
			if (typeof p == "object") {
				p = Ext.urlEncode(p);
			}
			if(p){
				url += (url.indexOf('?') != -1 ? '&' : '?') + p;
			}

			return url;
		},

		gotoPage : function(url) {
			if (url.indexOf(this.getContextPath()) != 0) {
				if (url.indexOf('/') != 0) {
					url = '/' + url;
				}
				url = this.getContextPath() + url;
			}
			document.location = url;
		},

		getSession : function() {
			return window.top.application.getApplicationContext();
		},

		setRequestParameter : function(para) {
			window.top.REQUEST_PARAMETER = para;
		},

		getRequestParameter : function() {
			return window.top.REQUEST_PARAMETER;
		},
		
		getDate : function(flag,date){
			if(date == undefined){
				date = formatDate(new Date());
			}
			if("start" == flag){
				return date + " 00:00:00";
			}else if("end" == flag){
				return date + " 23:59:59";
			}
		},

		setWFApproveDimension : function(width,height){
			parent.Appframe.workflow.WorkList.setWidth(width,height);
		},
		
		showMessage : function(msg) {
			var opt = {
				title : '消息',
				buttons : Ext.Msg.OK,
				icon : Ext.MessageBox.INFO
			};
			if (typeof(msg) == 'string') {
				opt.msg = msg;
			} else if (typeof(msg) == 'object') {
				Ext.applyIf(opt, msg);
			}
			Ext.MessageBox.show(opt);
		},

		showError : function(msg) {
			var opt = opt = {
				title : '错误',
				buttons : Ext.Msg.OK,
				icon : Ext.MessageBox.ERROR
			};
			if (typeof(msg) == 'string') {
				opt.msg = msg;
			} else if (typeof(msg) == 'object') {
				Ext.applyIf(opt, msg);
			}
			Ext.MessageBox.show(opt);
		},

		showException : function(msg, stack) {
			if (!stack || stack === 'undefined') {
				this.showError(msg);
				return;
			}
			var dlg = new Ext.Window({
				autoCreate : true,
				title : '异常',
				resizable : true,
				constrain : false,
				constrainHeader : true,
				minimizable : false,
				maximizable : false,
				stateful : false,
				modal : true,
				shim : true,
				buttonAlign : "center",
				// layout : 'fit',
				width : 700,
				height : 300,
				closeAction : 'hide',
				plain : true,

				buttons : [{
					text : 'Close',
					handler : function() {
						dlg.hide();
					}
				}, {
					text : 'Copy to Clipboard',
					handler : function() {
						var textareaEl = Ext.get('expCt');
						ExtJ.copyToClipboard(textareaEl.dom.innerText || textareaEl.dom.textContent);
					}
				}]
			});
			dlg.render(document.body);
			dlg.getEl().addClass('x-window-dlg');
			bodyEl = dlg.body.createChild({
				html : '<div class="ext-mb-icon"></div><div class="ext-mb-content"><span class="ext-mb-text"></span><br/><div id="expCt" style="width:100%;height:90%;overflow:auto;"></div></div>'
			});
			iconEl = Ext.get(bodyEl.dom.firstChild);
			iconEl.removeClass('x-hidden');
			iconEl.replaceClass('', Ext.MessageBox.ERROR);
			var contentEl = bodyEl.dom.childNodes[1];
			msgEl = Ext.get(contentEl.firstChild);
			textareaEl = Ext.get(contentEl.childNodes[2]);
			textareaEl.enableDisplayMode();
			bodyEl.createChild({
				cls : 'x-clear'
			});

			msgEl.update(msg || 'System Error&#160;');
			textareaEl.update(stack || '&#160;');

			dlg.show();
			dlg.setSize(dlg.getSize());
		},

		doExport : function(config) {
			var n = "_exportIFrame_";
			var f = document.getElementById(n);
			if (!f) {
				f = document.createElement("IFRAME");
				f.style.width = '0px';
				f.style.height = '0px';
				document.body.appendChild(f);
			}
			var requestURL = config.url;
			if (config.params) {
				requestURL = requestURL + '?' + Ext.urlEncode(config.params);
			}
			f.src = encodeURI(requestURL);
//			window.open(requestURL);
		},
		copyToClipboard : function(txt) {
			var bodyEl = Ext.getBody();
			var holder = Ext.get('clipboardHolder');
			if (!holder) {
				bodyEl.createChild({
					tag : "textarea",
					id : 'clipboardHolder',
					style : {
						visbility : "hidden",
						display : 'none'
					}
				});
				holder = Ext.get('clipboardHolder');
			}
			if (Ext.isIE) {
				holder.dom.innerText = txt;
				Copied = holder.dom.createTextRange();
				Copied.execCommand("Copy");
			} else if (window.clipboardData) {
				window.clipboardData.clearData();
				window.clipboardData.setData("Text", txt);
			} else if (navigator.userAgent.indexOf("Opera") != -1) {
				window.location = txt;
			} else if (window.netscape) {
				try {
					netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
				} catch (e) {
					alert("Your firefox limits clipboard operation，please open adress 'about:config' and set 'signed.applets.codebase_principal_support' = true then try again.");
					return false;
				}
				var clip = Components.classes['@mozilla.org/widget/clipboard;1']
						.createInstance(Components.interfaces.nsIClipboard);
				if (!clip)
					return;
				var trans = Components.classes['@mozilla.org/widget/transferable;1']
						.createInstance(Components.interfaces.nsITransferable);
				if (!trans)
					return;
				trans.addDataFlavor('text/unicode');
				var str = new Object();
				var len = new Object();
				var str = Components.classes['@mozilla.org/supports-string;1']
						.createInstance(Components.interfaces.nsISupportsString);
				var copytext = new String(txt);
				str.data = copytext;
				trans.setTransferData("text/unicode", str, copytext.length * 2);
				var clipid = Components.interfaces.nsIClipboard;
				if (!clip)
					return false;
				clip.setData(trans, null, clipid.kGlobalClipboard);
			}
		}
	};
}();

Ext.namespace("ExtJ");
Ext.namespace("ExtJ.dialog");
Ext.namespace("ExtJ.tree");
Ext.namespace("ExtJ.form");
Ext.namespace("ExtJ.form.Action");

ExtJ.form.Action.Submit = function(form, options) {
	ExtJ.form.Action.Submit.superclass.constructor.call(this, form, options);
};
Ext.extend(ExtJ.form.Action.Submit, Ext.form.Action.Submit, {
	type : 'submit',

	success : function(response) {
		this.result = this.processResponse(response);
		if (this.result === true || this.result.success) {
			this.form.afterAction(this, true);
			return;
		}
		this.form.afterAction(this, false);

		var msg = this.result.ERROR_MSG;
		var stack = this.result.ERROR_STACK;

		if (msg) {
			ExtJ.showException(msg, stack);
		}

		if (this.result.errors) {
			if (this.result.errors instanceof Array) {
				for (var i = 0, len = this.result.errors.length; i < len; i++) {
					var fieldError = this.result.errors[i];
					ExtJ.showError(fieldError.msg);
					break;
				}
			}
			this.failureType = Ext.form.Action.SERVER_INVALID;
		}
	}
});

Ext.form.Action.ACTION_TYPES['submit'] = ExtJ.form.Action.Submit;

Ext.Ajax.on('requestexception', function(conn, response, options) {
	try{
		var result = Ext.decode(response.responseText);
		var msg = result.ERROR_MSG;
		var stack = result.ERROR_STACK;
	
		ExtJ.showException(msg, stack);
	}catch(e){
		
	}
});


Ext.layout.FormLayout.prototype.renderItem = function(c, position, target) {
	if (c && !c.rendered && c.isFormField && c.inputType != 'hidden') {
		var b = c.allowBlank ? '' : '<span style="color:red">*</span>';
		var a = c.fieldLabel + b;

		var args = [
				c.id,
				a,
				c.labelStyle || this.labelStyle || '',
				this.elementStyle || '',
				typeof c.labelSeparator == 'undefined'
						? this.labelSeparator
						: c.labelSeparator,
				(c.itemCls || this.container.itemCls || '')
						+ (c.hideLabel ? ' x-hide-label' : ''),
				c.clearCls || 'x-form-clear-left'];
		if (typeof position == 'number') {
			position = target.dom.childNodes[position] || null;
		}
		if (position) {
			this.fieldTpl.insertBefore(position, args);
		} else {
			this.fieldTpl.append(target, args);
		}
		c.render('x-form-el-' + c.id);
	} else {
		Ext.layout.FormLayout.superclass.renderItem.apply(this, arguments);
	}
};

/**
 * 加载表格组件时对BODY生成MASK
 */
Ext.grid.GridPanel.prototype.initEvents = function() {
	Ext.grid.GridPanel.superclass.initEvents.call(this);

	if (this.loadMask) {
		this.loadMask = new Ext.LoadMask(Ext.getBody(), Ext.apply({
			store : this.store
		}, this.loadMask));
	}
};

Ext.override(Ext.form.BasicForm, {

	setReadOnly : function(bReadOnly) {
		this.items.each(function(f) {
			if (f.isFormField) {
				// f.getEl().dom.readOnly = bReadOnly;
				f.readOnly = bReadOnly;
				// TriggerFields need to have the "trigger" button disabled
				if (f instanceof Ext.form.TriggerField) {
					f.setDisabled(bReadOnly);
					if (f instanceof Ext.form.ComboBox)
						// Alternatively, to check if combobox
						// use: if (f.setEditable)...
						f.setEditable(!bReadOnly);
				}
			}
		});
	}
});